package env

import (
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/joho/godotenv"
	"github.com/segmentio/go-snakecase"
)

func init() {
	_ = godotenv.Load()
}

var prefix string

func getEnv(key string) string {
	if key == "" {
		return ""
	}
	fixedKey := key
	if prefix != "" {
		fixedKey = strings.TrimSuffix(prefix, "_") + "_" + strings.ToUpper(snakecase.Snakecase(fixedKey))
	}
	return os.Getenv(fixedKey)
}

func Prefix(p string) {
	prefix = p
}

func GetString(key string, defaultValue ...string) string {
	if s := getEnv(key); s != "" {
		return s
	}
	if len(defaultValue) > 0 {
		for _, v := range defaultValue {
			if v != "" {
				return v
			}
		}
	}
	return ""
}

func GetInt(key string, defaultValue ...int64) int64 {
	if s := getEnv(key); s != "" {
		if v, err := strconv.ParseInt(s, 10, 64); err == nil {
			return v
		}
	}

	if len(defaultValue) > 0 {
		for _, v := range defaultValue {
			if v != 0 {
				return v
			}
		}
	}
	return 0
}

func GetFloat(key string, defaultValue ...float64) float64 {
	if s := getEnv(key); s != "" {
		if v, err := strconv.ParseFloat(s, 64); err == nil {
			return v
		}
	}
	if len(defaultValue) > 0 {
		for _, v := range defaultValue {
			if v != 0 {
				return v
			}
		}
	}
	return 0
}

func IsTrue(key string) bool {
	if s := getEnv(key); s != "" {
		if v, err := strconv.ParseBool(s); err == nil {
			return v
		}
	}
	return false
}

func IsFalse(key string) bool {
	if s := getEnv(key); s != "" {
		if v, err := strconv.ParseBool(s); err == nil {
			return !v
		}
	}
	return false
}

func GetDuration(key string, defaultValue ...time.Duration) time.Duration {
	if s := getEnv(key); s != "" {
		if v, err := time.ParseDuration(s); err == nil {
			return v
		}
	}
	if len(defaultValue) > 0 {
		for _, v := range defaultValue {
			if v != 0 {
				return v
			}
		}
	}
	return 0
}